package com.beardedcoder.utils.db.other;
import java.util.ArrayList;
import java.util.List;



public class DbTable {
	private static final String CREATE_TABLE_START = "CREATE TABLE ";
	private String tableName;
	private ArrayList<DbField> tableFields = null;

	public DbTable (String tableName) {
		this.tableName = tableName;
	}
	
	private boolean isFieldsPresent() {
		if (tableFields == null) return false;
		if (tableFields.size() == 0) return false;
		return true;
		
	}
	
	public void addField(DbField field) {
		ensureFieldArrayInitialised();
		tableFields.add(field);
	}
	
	public void addAllFields(List<DbField> fields) {
		ensureFieldArrayInitialised();
		this.tableFields.addAll(fields);
	}

	private void ensureFieldArrayInitialised() {
		if (!isFieldsPresent()) {
			this.tableFields = new ArrayList<DbField>();
		}
	}
	
	public String generateTableCreationSQL () throws Exception {
		if (!isFieldsPresent()) {
			throw new Exception("no fields in table :: " + tableName);
		}
		StringBuffer sb = new StringBuffer();
		sb.append(CREATE_TABLE_START);
		sb.append(tableName).append(" (");
		for (DbField field : tableFields) {
			sb.append(field.getFieldNameAndType());
			if (!field.lastField) {
				sb.append(", ");
			}
		}
		
		return sb.toString();
	}
}